﻿using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace TotalApplication.AngelSix
{
    /// <summary>
    /// Create a clipping region from the parent <see cref="Border"/> <see cref="CornerRadius"/>
    /// </summary>
    public class ClipFromBorderProperty : BaseAttachedProperty<ClipFromBorderProperty, bool>
    {
        #region Private Members

        private SizeChangedEventHandler? _borderSizeChanged;
        private RoutedEventHandler? _borderLoaded; 

        #endregion

        public override void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var self = sender as FrameworkElement;
            if (self == null) return;

            if (!(self.Parent is Border border))
            {
                Debugger.Break();
                return;
            }

            _borderLoaded = (s1, e1) => Border_OnChanged(s1, e1, self);

            _borderSizeChanged = (s1, e1) => Border_OnChanged(s1, e1, self);

            // If true, hook into events
            if ((bool)e.NewValue) 
            {
                border.Loaded += _borderLoaded;
                border.SizeChanged += _borderSizeChanged;
            }
            // Else, unhook
            else
            {
                border.Loaded -= _borderLoaded;
                border.SizeChanged -= _borderSizeChanged;
            }
        }

        private void Border_OnChanged(object sender, RoutedEventArgs e, FrameworkElement child)
        {
            var border = (Border)sender;
            if (border == null) return;

            // Check we have an actual size
            if(border.ActualWidth == 0 && border.ActualHeight == 0) return;

            // Setup the new child clipping area
            var rect = new RectangleGeometry();
            rect.RadiusX = rect.RadiusY = Math.Max(0, border.CornerRadius.TopLeft - (border.BorderThickness.Left * 0.5));

            // Set rectangle size to match child's actual size
            rect.Rect = new Rect(child.RenderSize);

            // Assign clipping area tp the child
            child.Clip = rect;
                
        }

    }
}
